package com.zhang.common.redis;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.PostConstruct;

/**
 * RedisPool
 *
 * @author zhangxin
 * @date 2021/5/20
 */
@Component
public class RedisPool {
    private static JedisPool pool = null;

    @Value("${spring.redis.jedis.pool.maxTotal:100}")
    private Integer maxTotal;

    @Value("${spring.redis.jedis.pool.maxIdle:5}")
    private Integer maxIdle;

    @Value("${spring.redis.jedis.pool.maxWait:100000}")
    private Integer maxWait;

    @Value("${spring.redis.database:0}")
    private Integer database;

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.port:6379}")
    private Integer port;

    public RedisPool() {
    }

    public static Jedis getJedis() {
        return pool != null ? pool.getResource() : null;
    }

    private static void configure(Integer maxTotal, Integer maxIdle, Integer maxWait, String host, Integer port, String password, Integer database) {
        if (pool == null) {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(maxTotal);
            config.setMaxIdle(maxIdle);
            config.setMaxWaitMillis(maxWait.longValue());
            config.setTestOnBorrow(true);
            pool = new JedisPool(config, host, port, maxWait, password, database);
        }
    }

    @PostConstruct
    public void init(){
        if (RedisUtil.HAS_REDIS) {
            configure(maxTotal, maxIdle, maxWait, host, port, password, database);
        }
    }
//    static {
//        if (RedisUtil.HAS_REDIS) {
//            configure();
//        }
//
//    }
}
